import React, { useState } from 'react';
import { Collapse } from 'antd-mobile';
import { Common } from 'UtilsCommon';
import Base from './base';

const setRowData = (properties, rowData, property, pageAxis) => {
    const list = [];
    properties.forEach(p => {
        if (!Common.isNullOrEmpty(rowData[p.name])) p.value = rowData[p.name];
        p.data = rowData;
        if (p.properties) setRowData(p.properties, rowData, property, pageAxis);
        if (property.expendSetData) pageAxis.getFunction(property.expendSetData)({ property, p, rowData });
    });
    return list;
};

const renderPanel = (property, v, i, pageId, pageAxis) => {
    const title = v[property.titleName];
    const view = Common.clone({ properties: property.properties });
    setRowData(view.properties, v, property, pageAxis);
    return <Collapse.Panel key={i} title={title}>
        {Base.renderProperties2(view.properties, property, pageId)}
    </Collapse.Panel>;
};

const getActiveKey = (value) => {
    if (value.length === 0) return null;
    const keys = [];
    for (let i = 0; i < value.length; i++) {
        keys.push(i.toString());
    }
    return keys;
};

export default React.memo((props) => {
    const { property, pageId, pageAxis } = Base.getProps(props);
    const [value, setValue] = useState(Base.getInitValue(property) || []);

    const [isVisible, setIsVisible] = useState(property.isVisible !== false);

    property.setIsVisible = (v) => { property.isVisible = v; setIsVisible(v); };
    property.setValue = (v) => setValue(v);

    if (!isVisible) return null;

    const defaultActiveKey = getActiveKey(value);

    return <div className={property.className} style={Base.setStyle(property.style)}>
        {value.length > 0 && <Collapse defaultActiveKey={defaultActiveKey}>
            {value.map((v, i) => renderPanel(property, v, i, pageId, pageAxis))}
        </Collapse>}
    </div>;
});